package com.github.chirspan.xaas.core.template;

import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ************************
 * <p></p>
 * *************************
 *
 * @author chenpan
 * @date 2021/2/2 13:35
 */
public class StringTemplate {

    private static final TemplateEngine ENGINE = TemplateUtil.createEngine(new TemplateConfig());

    public static final String PARENT_KEY = "$p";

    public static String render(String templateStr, Map<String, Object> params) {
        Template template = ENGINE.getTemplate(templateStr);
        return template.render(params);
    }

    public static String renderString(String str) {
        return render(str, getStringParam(str));
    }


    private static Map<String, Object> getStringParam(String sql) {
        Map<String, Object> map = new HashMap<>();
        String reg = "\\$\\{(.*?)\\}";
        Pattern pattern = Pattern.compile(reg);
        // 内容 与 匹配规则 的测试
        Matcher matcher = pattern.matcher(sql);

        while (matcher.find()) {
            map.put(matcher.group(1), "0");
        }
        return map;
    }

    public static void main(String[] args) {
        String template = "<DATA><LOCAL_ID>${pv1_info[0].pid}</LOCAL_ID></DATA>";
        String json = "{\"pv1_info\": [{\n" +
                "\t\t\t\"pat_visit_type\": 2,\n" +
                "\t\t\t\"pid\": 12470072,\n" +
                "\t\t\t\"pvid\": 1,\n" +
                "\t\t\t\"dept_id\": 432}]}";
        Map<String, Object> params = (Map<String, Object>) JSON.parseObject(json);
        System.out.println(render(template, params));
    }
}
